package org.hnzyx.joggle.server;

import org.hnzyx.joggle.cache.DefaultCacheOperationManager;
import org.hnzyx.joggle.common.CacheKye;
import org.hnzyx.joggle.common.CommonVariable;
import org.hnzyx.joggle.config.CustomProperties;
import org.hnzyx.joggle.exceptions.ErrorException;
import org.hnzyx.joggle.exceptions.RefuseRequestException;
import org.hnzyx.joggle.exceptions.ReplayRequestException;
import org.hnzyx.joggle.exceptions.RequestTimeErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class ReplayServer {

    @Autowired
    private DefaultCacheOperationManager defaultCacheOperationManager;

    @Autowired
    private CustomProperties customProperties;


    public void check(HttpServletRequest request) throws RefuseRequestException, RequestTimeErrorException, ReplayRequestException, ErrorException {
        // 这两个值通过请求参数 传入 通过加签验签判断是否篡改过,保证安全性
        String requestTime = request.getParameter(CommonVariable.REQUEST_TIME);
        String nonce = request.getParameter(CommonVariable.NONCE);
        if (StringUtils.isEmpty(nonce) || StringUtils.isEmpty(requestTime)){
            throw new RefuseRequestException();
        }
        Long aLong = Long.valueOf(requestTime);// 请求时间
        long l = System.currentTimeMillis(); // 服务器当前时间
        // 请求时间应该小于当前时间 并且请求时间加上超时时间 应该大于当前时间
        if (aLong < l && (aLong + customProperties.getReplayTime()) > l){
            String accessKye = request.getHeader(CommonVariable.ACCESS_KEY);
            this.setKye(accessKye, nonce);
        } else {
            throw new RequestTimeErrorException();
        }
    }

    private void setKye(String accessKye, String nonce) throws ErrorException, ReplayRequestException {
        String value = defaultCacheOperationManager.getKey(CacheKye.joggleNonce + accessKye + CommonVariable.MO + nonce);
        if (StringUtils.isEmpty(value)){
            // 不存在该请求 则通过
            String s = defaultCacheOperationManager.setKey(CacheKye.joggleNonce + nonce, "", customProperties.getReplayTime() * 2);
            if (!CommonVariable.OK.equalsIgnoreCase(s)) throw new ErrorException();
        } else {
            throw new ReplayRequestException();
        }


    }
}
